$(function () {
    let timer;
    let removeImg = $(".remove-img");
    let deleteImg = $(".delete-img");
    let shoppingCart = new Shopping_cart();

    $(".choose-product").change(function () {
        let checkboxes = $(".new-product");
        checkboxes.prop("checked", $(this).prop("checked"));
        let id = $(this).attr("information-id");
        if (checkboxes.prop("checked")) {
            shoppingCart.updateAllSelectedStatus(id, 1).then(function (res) {
                location.reload()
            })
        } else {
            shoppingCart.updateAllSelectedStatus(id, 0).then(function (res) {
                location.reload()
            })
        }
    });
    $(".drop-down-menu").on({
        mouseenter: function () {
            $(".options-img").attr({"src": "http://localhost:8083/resource_packs/images/drop_down_color.png"})
            $(".more").css({"display": "block"})
        }, mouseleave: function () {
            $(".options-img").attr({"src": "http://localhost:8083/resource_packs/images/drop_down.png"})
        }
    });

    $(".drop-down").on({
        mouseenter: function () {
            // 取消之前设置的延迟执行
            clearTimeout(timer);
            let boxId = $(this);
            // 设置延迟执行操作
            timer = setTimeout(function () {
                // 在延迟时间后执行操作
                if ($(boxId[0]).attr("class") !== "more drop-down") {
                    $(".more").css({"display": "none"})
                }
            }, 2000);
            // 设置延迟时间（单位为毫秒）
        },
        mouseleave: function () {
            // 取消之前设置的延迟执行
            clearTimeout(timer);

            let boxId = $(this);
            if ($(boxId[0]).attr("class") !== "more drop-down" &&
                $(boxId[0]).attr("class") !== "username options drop-down") {
                $(".more").css({"display": "none"})
            }
        }
    });

    $(".more").on({
        mouseenter: function () {
            $(".more").css({"display": "block"})
        },
        mouseleave: function () {
            $(".more").css({"display": "none"})
        }
    });


    deleteImg.on({
        mouseenter: function () {
            $(this).attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes_red.png"})
        },
        mouseleave: function () {
            $(this).attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes.png"})
        }
    });
    removeImg.on({
        mouseenter: function () {
            $(this).attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes_red.png"})
        },
        mouseleave: function () {
            $(this).attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes.png"})
        }
    });
    let shoppingCartId = null;
    removeImg.on("click", function () {
        $($(".hint-remove")).css({
            "display": "none"
        })

    })
    deleteImg.on("click", function () {
        shoppingCartId = $(this).attr("shopping-cart-id");
        $($(".hint-remove")[1]).css({
            "display": "block"
        })
    })
    $(".remove-button").on("click", function () {
        $(".hint-remove").css({
            "display": "none"
        })
    })
    $(".cancel").on("click", function () {
        $(".hint-remove").css({
            "display": "none"
        })
    })
    $(".commodity").on({
        mouseenter: function () {
            console.log($(this).children(":last"))
            $(this).children(":last").css("display", "block")
        },
        mouseleave: function () {
            $(this).children(":last").css({
                "display": "none"
            })
            $(this).children(":last").removeAttr("style")
        }
    });
    $(".login-button").on("click", function () {
        window.location.href = "http://localhost:8083/www.xiaomi.com/login"
    })
    $(".go-shopping").on("click", function () {
        window.location.href = "http://localhost:8083/www.xiaomi.com/shop"
    })
    $(".empty-go-shopping").on("click", function () {
        window.location.href = "http://localhost:8083/www.xiaomi.com/shop?acccount="+$(this).attr("account-id")
    })

    let indexUtil = new Index();
    $(".login-out").on("click", function () {
        indexUtil.logOut().then(function () {
            location.reload();
        })
    })

    $(".new-product").on("click", function () {
        let allChecked = $(".new-product").length === $(".new-product:checked").length;

        if (allChecked) {
            $(".choose-product").prop("checked", false);
        }
        if ($(this).prop("checked")) {
            shoppingCart.updateSelectedStatus($(this).attr("shopping-cart-id"), 1).then(res => {
                location.reload();
            })
        } else {
            shoppingCart.updateSelectedStatus($(this).attr("shopping-cart-id"), 0).then(res => {
                location.reload();
            })
        }
    })
    //增加购物车数量
    $(".new-add").on("click", function () {
        let number = $(this).prev().children().val();
        let inventory = $(this).attr("details-inventory");
        let purchaseLimit = $(this).attr("purchase-limit");
        let id = $(this).attr("shopping-cart-id");
        let addNumber = parseInt(number) + 1;
        if (parseInt(number) >= parseInt(purchaseLimit)) {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("商品加入购物车数量超过限购数")
        } else if (number >= parseInt(inventory)) {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("商品加入购物车数量超过库存数")
        } else {
            //修改数量
            shoppingCart.updateQuantity(id, addNumber).then(res => {
                location.reload();
            })
        }
    })
    //减少购物车数量
    $(".new-reduce").on("click", function () {
        let number = $(this).next("").children().val();
        let reduceNumber = parseInt(number) - 1;
        let id = $(this).attr("shopping-cart-id");
        console.log(number)
        console.log(parseInt(number) === 1)
        if (parseInt(number) === 1) {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("修改数量不能小于0")
        } else {
            //修改数量
            shoppingCart.updateQuantity(id, reduceNumber).then(res => {
                location.reload();
            })
        }
    })
    //修改购物车数量
    let valueUtil = new Value_util();
    $(".number").on("blur", function () {
        let number = $(this).val();
        let type = valueUtil.isIntegerOrString(number);
        let id = $(this).attr("shopping-cart-id");
        let inventory = $(this).attr("details-inventory");
        let purchaseLimit = $(this).attr("purchase-limit");
        //判断是否超过限购数量
        if (parseInt(number) >= parseInt(purchaseLimit)) {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("商品加入购物车数量超过限购数")
            $(this).val(1)
            //判断是否超过库存数量
        } else if (number >= parseInt(inventory)) {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("商品加入购物车数量超过库存数")
            $(this).val(1)
            //判断输入的是否是数字
        } else if (type === "string") {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("请输入数字")
            $(this).val(1)
            //判断是否低于0
        } else if (number <= 0) {
            $($(".hint-remove")[0]).css("display", "block")
            $($(".remove-word")[0]).text("修改数量不能小于0")
            $(this).val(1)
        } else {
            //修改数量
            shoppingCart.updateQuantity(id, number).then(res => {
                location.reload();
            })
        }
    })
    //加入购物车
    $(".add-shopping").on("click", function () {
        let commoditiesId = $(this).attr("commodities-id");
        let informationId = $(this).attr("information-id");
        let commodityId = $(this).attr("commodity-id");
        //添加购物车
        shoppingCart.addToShoppingCart(informationId, commoditiesId, commodityId).then(res => {
            if (valueUtil.processContainsSpaces(res) === "false") {
                //没有登陆
                console.log(1)
                window.location.href = "http://localhost:8083/www.xiaomi.com/login"
            } else {

                location.reload();
            }
        })
    })
    //购物车删除商品
    $($(".remove-button")[1]).on("click", function () {
        shoppingCart.deleteFromShoppingCart(shoppingCartId).then(res => {
            console.log(res);
            location.reload();
        })
    })
    //图片悬浮切换
    $(".delete-insurance-img").on({
        mouseenter: function () {
            $(this).attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes_red.png"})
        },
        mouseleave: function () {
            $(this).attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes.png"})
        }
    });
    //删除指定商品保险
    $(".delete-insurance-img").on("click", function () {
        //删除多个Id中的其中一个
        let ids = valueUtil.removeMultipleIdOne($(this).attr("commodity-insurance-ids"),
            $(this).attr("commodity-insurance-id"));
        let shoppingCartId = $(this).attr("shopping-cart-id");
        //修改商品Ids
        shoppingCart.updateInsuranceIds(shoppingCartId, ids).then(res => {
            console.log(res)
            location.reload();
        })
    })

    $(".insurance-article-checkbox").on("click", function () {
        if ($(this).prop("checked")) {
            $(".sure-button-window").css({
                "color": "#ffffff",
                "background-color": "#FF6700",
                "border": " 1px solid #FF6700"
            })
        } else {
            $(".sure-button-window").css({
                "color": "#b0b0b0",
                "background-color": "#E0E0E0",
                "border": " 1px solid #E0E0E0"
            })
        }
    })
    let informationIds = null;
    let shoppingCartItemsId = null;
    $(".not-selected-commodity-insurance").on("click", function () {
        $($(".hint-remove")[2]).css("display", "block")
        let commodityInsurance = new Commodity_insurance();
        commodityInsurance.getInsuranceWithRelatedTablesById($(this).attr("commodity-insurance-id")).then(res => {
            console.log(JSON.parse(res))
            informationIds = $(".not-selected-commodity-insurance").attr("information-ids");
            shoppingCartItemsId = $(".not-selected-commodity-insurance").attr("shopping-cart-id")
            let commodityInsurance = JSON.parse(res);
            $(".sure-button-window").attr("insurance-id",commodityInsurance.insuranceId)
            $(".insurance-img-window img").attr("src", "http://localhost:8083/resource_packs/images/"
                + commodityInsurance.insuranceType.insuranceTypeLogo)
            $(".insurance-body-title").text(commodityInsurance.insuranceTitle)
            if (commodityInsurance.addPrice === undefined) {
                $(".insurance-desc-window").html(commodityInsurance.insuranceContext +
                    "<a class='insurance-price-window'>免费</a>")
            } else {
                $(".insurance-desc-window").html(commodityInsurance.insuranceContext +
                    "<a class='insurance-price-window'>" + commodityInsurance.addPrice + "元</a>")
            }

        })
    })
    $(".sure-button-window").on("click", function () {
        if ($(this).css("border") === "1px solid rgb(255, 103, 0)") {
            // 拆分成一个id数组
            let idArray = informationIds ? informationIds.split(",") : [];
            idArray.push($(this).attr("insurance-id").toString());
            // 将id数组转换回字符串形式，使用逗号进行分隔
            let newIds = idArray.join(",");
            //修改商品Ids
            shoppingCart.updateInsuranceIds(shoppingCartItemsId, newIds).then(res => {
                console.log(res)
                location.reload();
            })
        }
    })
    $(".settlement-price").on("click",function () {
        if ($(this).attr("is-items-shopping-cart-selected") === "true"){
            //加密
            let aesKeyUtil = new Aes_key_util();
            const encryptedInformationId = aesKeyUtil.encrypt($(this).attr("information-id"));
            window.location.href = "/www.xiaomi.com/order/settlement?informationId="+encodeURIComponent(encryptedInformationId)+"&account="+
                $(this).attr("account-id")
        }
    })
})